package com.image.demo.common.utils;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;

@SuppressWarnings("all")
public class ImgCompress {
	
	public static File compressImageByQality(File file, float qality, File outFile) throws IOException {
		if (!file.exists()) {
			return null;
		}
		
		if (outFile.exists()) {
			outFile.delete();
		}
		
		outFile.getParentFile().mkdirs();
		outFile.createNewFile();

		BufferedImage src = null;
		FileOutputStream out = null;
		
		ImageWriter imgWrier;
		ImageWriteParam imgWriteParams;
		
		imgWrier = ImageIO.getImageWritersByFormatName("jpg").next();
		imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);
		imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT);
		imgWriteParams.setCompressionQuality(qality);
		imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED);
		
		ColorModel colorModel = ImageIO.read(file).getColorModel();
		imgWriteParams.setDestinationType(
				new javax.imageio.ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(32, 32)));

		src = ImageIO.read(file);
		out = new FileOutputStream(outFile);
		
		imgWrier.reset();
		imgWrier.setOutput(ImageIO.createImageOutputStream(out));
		imgWrier.write(null, new IIOImage(src, null, null), imgWriteParams);
		
		out.flush();
		out.close();

		return outFile;
	}
	
	public static void main(String[] args) throws IOException {
		String path = "F:\\test/1098370507.jpg";
		String outPath = "F:\\test/img1.jpg";
		ImgCompress.compressImageByQality(new File(path), 0.1f, new File(outPath));
	}
}
